package com.alkaid.user.controller;

import com.alkaid.commons.entity.User;
import com.alkaid.commons.param.user.ChangePasswordParam;
import com.alkaid.commons.param.user.CheckNicknameParam;
import com.alkaid.commons.param.user.RegParam;
import com.alkaid.commons.utils.JsonResult;
import com.alkaid.commons.utils.JwtUtils;
import com.alkaid.user.service.UserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Kylin
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/reg")
    public JsonResult<Void> reg(@Validated RegParam regParam) {
        userService.reg(regParam.getNickname(), regParam.getPassword(), regParam.getMobile(), regParam.getSmsCode());
        return new JsonResult<>(200, null, "注册成功");
    }

    @GetMapping("/get_info")
    public JsonResult<User> getInfo(HttpServletRequest request) {
        String jwt = request.getHeader("Authorization");
        User userDO = userService.getUser(jwt);
        return new JsonResult<>(200, userDO, "success");
    }

    @PutMapping("/info")
    public JsonResult<Void> setInfo(HttpServletRequest request, @Validated User user, Long birthday) {
        String jwt = request.getHeader("Authorization");
        user.setBirth(new Date(birthday));
        userService.setUserInfo(jwt, user);
        return new JsonResult<>(200, null, "修改成功");
    }

    @PostMapping("/check_nickname")
    public JsonResult<Boolean> checkNickname(@Validated CheckNicknameParam param) {
        Boolean bool = userService.checkNickname(param.getNickname());
        return new JsonResult<>(200, bool, "查询成功");
    }

    @PutMapping("/avatar")
    public JsonResult<Void> setAvatar(HttpServletRequest request, String avatar) {
        String jwt = request.getHeader("Authorization");
        userService.setAvatar(jwt, avatar);
        return new JsonResult<>(200, null, "success");
    }

    @GetMapping("/pay")
    public JsonResult<String> pay(HttpServletRequest request) {
        String jwt = request.getHeader("Authorization");
        JwtUtils jwtUtils = new JwtUtils();
        jwtUtils.parseJwt(jwt);
        Long id = jwtUtils.getUser().getId();
        String newJwt = userService.pay(id);
        return new JsonResult<>(200, newJwt, "充值成功");
    }

    @PutMapping("/change_password")
    public JsonResult<Void> changePassword(HttpServletRequest request, @Validated ChangePasswordParam param) {
        String jwt = request.getHeader("Authorization");
        JwtUtils jwtUtils = new JwtUtils();
        jwtUtils.parseJwt(jwt);
        Long id = jwtUtils.getUser().getId();
        userService.changePassword(id, param);
        return new JsonResult<>(200, null, "修改密码成功，请重新登陆！");
    }
}
